package com.gdx.game.screen.base;

import com.badlogic.gdx.Gdx;
import com.badlogic.gdx.Screen;
import com.badlogic.gdx.graphics.OrthographicCamera;
import com.badlogic.gdx.graphics.g2d.SpriteBatch;
import com.badlogic.gdx.scenes.scene2d.Stage;
import com.badlogic.gdx.scenes.scene2d.actions.Actions;
import com.badlogic.gdx.utils.viewport.StretchViewport;
import com.badlogic.gdx.utils.viewport.Viewport;
import com.gdx.game.MyGame;
import com.gdx.game.resource.ResourceManager;

import java.util.concurrent.atomic.AtomicBoolean;

public abstract class BaseScreen implements Screen {

    protected final MyGame game;  //游戏实例
    protected final ResourceManager rm;  //资源

    protected OrthographicCamera cam;//直角正交摄像机

    protected Stage stage;//screen将会放置在舞台中

    protected final Viewport viewport;//可视区域

    protected AtomicBoolean clickable = new AtomicBoolean(true){};//切屏过程中禁用点击
    protected AtomicBoolean renderBatch = new AtomicBoolean(false){};//切屏过程中禁用 batch 渲染

    public BaseScreen(final MyGame game, final ResourceManager rm) {
        this.game = game;
        this.rm = rm;
        cam = new OrthographicCamera(MyGame.V_WIDTH, MyGame.V_HEIGHT);
        cam.setToOrtho(false);
        viewport = new StretchViewport(MyGame.V_WIDTH, MyGame.V_HEIGHT, cam);
        stage = new Stage(viewport, game.batch);
    }

    @Override
    public void show() {
        Gdx.input.setInputProcessor(stage);
        renderBatch.set(true);
    }

    @Override
    public void render(float delta) {
        stage.act(delta); //根据时间流逝 执行舞台动作
        stage.draw();//绘制舞台动作
    }

    @Override
    public void resize(int width, int height) {

    }

    @Override
    public void pause() {

    }

    @Override
    public void resume() {

    }

    @Override
    public void hide() {

    }

    @Override
    public void dispose() {
        stage.dispose();
    }


    public Stage getStage() {
        return stage;
    }

    public OrthographicCamera getCamera() {
        return cam;
    }

    public SpriteBatch getBatch() {
        return game.batch;
    }

    public MyGame getGame() {
        return game;
    }


    public void setFadeScreen(final Screen screen) {
        if(clickable.get()) {
            clickable.set(false);
            renderBatch.set(false);
            stage.addAction(Actions.sequence(Actions.fadeOut(0.3f),
                    Actions.run(new Runnable() {
                        @Override
                        public void run() {
                            game.setScreen(screen);
                            renderBatch.set(true);
                            clickable.set(true);
                        }
                    })));
        }
    }

}
